import { computed, defineComponent, ref, toRaw } from 'vue';
import { Overlay, Progress, Toast } from 'vant';
import { useImageStore } from '@/domain/correction/hooks/image';
import { usePrepareStore } from '@/domain/correction/hooks/prepare';
import { saveLogic } from '@/domain/correction/core/prepare';
import { useCurrectStdStore } from '@/domain/correction/hooks/currectStd';
export default defineComponent({
  name: 'headerTopBar',
  setup() {
    const store = useImageStore();
    const isEditor = computed(() => store.state.isEditor);
    const saveStatus = ref('');
    const currectStore = useCurrectStdStore();
    const prepare = usePrepareStore();
    const editorStatus = ref(false);
    const percentage = ref(0);

    const changeStatus = async () => {
      /**保存 */
      if (isEditor.value) {
        /**获取批改状态 */
        const img_info = store.getCorrectImageStatus(currectStore.state.currentSubjectList);
        /**不验证批改小问状态 */
        // const info = homeWorkStore.getCorrectStatus();
        if (img_info.status) {
          /**loading */
          editorStatus.value = true;

          /**保存前清空参数列表 */
          currectStore.getReqParam()?.correct_infos?.forEach((node) => {
            node.img_urls = '';
          });
          percentage.value = 0;
          saveStatus.value = '';
          saveLogic(
            store.state.imageManages,
            (url, num) => {
              // 添加图像进入参数逻辑替换逻辑
              percentage.value = Math.floor(((num + 1) / store.state.imageManages.length) * 100);
              saveStatus.value = '正在上传中，完成进度' + percentage.value + '%';
              const pos = url.lastIndexOf('/');
              const name = url.substring(pos + 1);
              store.state.images.forEach((n) => {
                const opos = n.baseUrl.lastIndexOf('/');
                const baseName = n.baseUrl.substring(opos + 1);
                if (name === baseName) {
                  n.imgUrl = url;
                  currectStore.getReqParam()?.correct_infos?.forEach((node) => {
                    if (node.id === n.id) {
                      if (node.img_urls === '') {
                        node.img_urls = url;
                      } else {
                        node.img_urls = node.img_urls + ',' + url;
                      }
                    }
                  });
                }
              });
            },
            (text) => {
              Toast.fail(text);
              editorStatus.value = false;
            }
          ).subscribe({
            next: (status) => {
              if (status) {
                percentage.value = 100;
                editorStatus.value = false;
                store.state.isEditor = false;
                store.state.hasCurrect = true;
                //保存当前作业状态
                // window.localStorage.setItem('CurrectStdtate', JSON.stringify(toRaw(currectStore.state)));
                Toast.success('上传完成');
              } else {
                Toast.fail('上传批改图像失败，请耐心重新上传');
              }
            },
            error: (err) => {
              Toast.fail('上传失败，请重试');
              editorStatus.value = false;
            }
          });
          return;
        }
        /**不验证批改小问状态 */
        // if (!info.status) {
        //   Toast.fail(info.text);
        // }
        if (!img_info.status) {
          Toast.fail(img_info.text);
        }
      } else {
        /**进入编辑 */
        if (currectStore.state.currentStdHomeWork && currectStore.state.currentStdHomeWork.commit) {
          if (prepare.state.prepare && prepare.state.prepare.pre_work) {
            store.state.isEditor = true;
          } else {
            Toast.fail('未获取学生备课信息,请备课后再进入');
          }
        } else {
          Toast.fail('未获取学生提交图像信息');
        }
      }
    };

    return () => (
      <>
        <div class=" h-14 leading-r3 flex pl-4 pr-4 ">
          <i
            class={'text-r1.5 iconfont icon-fanhui1 cursor-pointer flex-initial leading-r3 ml-1 '}
            onClick={() => {
              window.history.back();
            }}
          ></i>
          <span class=" text-r1.7 leading-r3 flex-grow text-center">
            {currectStore.state.currentStdHomeWork?.stu_name || currectStore.state.currentStdHomeWork?.stu_id}
          </span>
          <span class=" inline-block  text-r1.3 leading-r3  cursor-pointer mr-1 flex-initial text-right" onClick={changeStatus}>
            {isEditor.value ? '保存' : '编辑'}
          </span>
        </div>
        <Overlay show={editorStatus.value}>
          <div class={'w-full h-28 absolute top-1/2 transform -translate-y-1/2 text-center'}>
            <span class={' block text-r1.4 text-gray-50'}>正在暂存批改图像</span>
            <br></br>
            <span class={' block text-r1.4 text-gray-50'}>{saveStatus.value}</span>
            <br></br>
            <Progress percentage={percentage.value}></Progress>
          </div>
        </Overlay>
      </>
    );
  }
});
